package com.opencee.cloud.uaa.provider.service;

import com.opencee.cloud.uaa.constants.UaaConstants;
import com.opencee.common.security.SecurityUser;
import com.opencee.common.utils.RedisTemplateUtil;
import com.opencee.common.utils.SpringContextHolder;
import com.opencee.common.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author yadu
 */
@Slf4j
@Service
public class QrCodeUserDetailService implements UserDetailsService {
    private TokenStore tokenStore;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    /**
     * 账号密码登录认证信息获取
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String code) throws UsernameNotFoundException {
        if (tokenStore == null) {
            // 防止循环依赖,此处使用静态方法获取bean
            tokenStore = SpringContextHolder.getBean(TokenStore.class);
        }
        Map<String, String> parameterMap = WebUtil.getParameterMap();
        String token = parameterMap.get("token");
        SecurityUser user = null;
        String key = UaaConstants.CACHE_LOGIN_QRCODE_KEY + code;
        if (StringUtils.isNotBlank(token) && redisTemplateUtil.hasKey(key)) {
            // 验证token有效性
            OAuth2Authentication authentication = tokenStore.readAuthentication(token);
            if (authentication != null) {
                user = (SecurityUser) authentication.getPrincipal();
                redisTemplateUtil.del(key);
            }
        } else {
            return null;
        }
        log.info("-----QrcodeUserDetailService------");
        return user;
    }
}
